<template>
  <div class="container">
    <header class="customHeaderStyle">
      <!-- <router-link :to="'/main/profile'"> -->
      <div class="go-back" @click="turn">
        <i></i>
        <i></i>
        <i></i>
      </div>
      <!-- </router-link>	 -->
      <div class="headerCustomTitle">向商家付款</div>
    </header>
    <div style="height:3rem;"></div>
    <div class="wrapper">
      <div class="inner">
        <!-- <canvas id="ean"></canvas> -->
        <qr-code id="qr" :text="message"></qr-code>
        <div class="pay_method">
          <i class="icon njfont nj-jinrong"></i>
          <div class="tip_1">使用钱包余额</div>
        </div>

      </div>
      <div class="tip_2">每分钟自动更新付款码</div>
    </div>
    <child ref="pro" @WxhpasswordPendingChange="handle" :cancelPassword="cancelOrderFn"></child>
  </div>
</template>
<script>
  import { mapMutations, mapActions, mapGetters } from "vuex";
  import VueQRCodeComponent from 'vue-qrcode-component'
  import Ean from '../../utils/WXH/ean13.js'
  import { Toast } from '../../utils/toast.js'
  import MD5 from '../../utils/md5_wxh.js'
  import child from '../../real-components/ConfirmOrder/ConfirmOrderPursekey'
  import test from './index.vue'
  import { MessageBox } from '../../ui-components'
  import {getWaitPayOffLineOrderInfo, walletPayOffLineOrder} from "../../api/wxh/getData.js"
  //获取钱包可用余额
  import {getWalletBalance} from "../Pay/axios";
  export default {
    name:"code_pay_new",
    data() {
      return {
        message: '', //二维码数据
        password: '',
        webSocket: '',
        result: '',
        timer: '',
        interval: '',
        flag: true,
        //已经获取到支付动作了，置为true，如果用户离开该页面就取消支付
        needCancelOrder: false,
        walletBalance: null,//钱包可用余额,
        intervalTiming: 3000,
      }
    },
    computed: {
      ...mapGetters('wxh', [
        'sessionId',
        'userInfo',
        'login'
      ])
    },
    components: {
      'qr-code': VueQRCodeComponent,
      child,
      test
    },
    mounted() {

    },
    async created() {
      await this.getUserInfo();
      await this.initData();
      //开启轮询
      this.startIntervalAjax();
    },
    beforeDestroy(){
      //是否需要取消订单
      if (this.needCancelOrder) {
        this.cancelOrderFn();
      }
      //取消轮询
      this.stopIntervalAjax();
    },
    methods: {
      ...mapActions('wxh', [
        'getUserInfo'
      ]),
      ...mapMutations('wxh', [
        'USER_INFO',
        'ClEAR_SESSIONID',
        'LOGO_OUT',
        'LOGO_IN',
        'CLEAR_INFO'
      ]),
      async initData() {
        await this.reFreshUserInfo(this);
        let info = {
          userId: this.userInfo.userid,
          phone: this.userInfo.mobile,
          vipname: this.userInfo.vipname,
          remainingscore: this.userInfo.remainingscore,
          sessionId:this.sessionId,
        }
        //二维码
        this.message = JSON.stringify(info);
        //条形码
        // let el = document.getElementById('ean');
        // let ea = new Ean(el, '1234566444644');

      },
      turn() {
        if(this.$route.query.Page) {
          this.$router.go(-1);
        } else {
          this.$router.push({
            name: 'profile'
          });
        }

      },
      //tep one: get the result of pos order;
      // "returnCode": 2,：没有待支付订单
      // "returnCode": 1,：成功查询出待支付订单信息
      // "returnCode": 0,：查询待支付订单异常
      async getOrderResult(){
        let req = await getWaitPayOffLineOrderInfo({});
        //获取到支付动作
        //1、需要结束轮询
        //2、将this.needCancelOrder置为true
        //注意：returnCode=0和2的时候代表没有拿到待支付订单，应该继续轮询，并且无需提示
        if(req.data.returnCode === 1){
          //结束掉轮询
          this.stopIntervalAjax();
          //将this.needCancelOrder置为true
          this.needCancelOrder = true;
          //判断余额是否足够
          //订单金额
          let realPay = parseFloat(req.data.data[0].realPay);
          //钱包可用余额
          let wallet = this.walletBalance;
          if (wallet === null) {
            try {
              wallet = (await getWalletBalance()).data.data[0].availAmount;
              this.walletBalance = wallet;
              console.log("获取钱包可用余额", wallet);
            } catch (err) {
              this.mToast("获取钱包余额发生错误", "fail");
              //开启轮询
              // this.startIntervalAjax();
              //取消这次支付动作
              this.sendStatus(4);
              return;
            }
          }
          // if (wallet < realPay) {
          //   this.mToast("钱包余额不足", "warn");
          //   //开启轮询
          //   // this.startIntervalAjax();
          //   //取消这次支付动作
          //   this.sendStatus(4);
          //   return;
          // }
          //is set password;
          if(this.userInfo.walletStatus === "0"){
            // no password;
            this.$router.push('/main/SetKeyWallet');
          }
          if(this.userInfo.walletStatus === "1"){
            //has password & need password;
            //免密金额小于订单金额，提示输入密码
            console.log("判断输入密码");
            if(parseFloat(this.userInfo.moneyWithoutCode) < realPay){
              console.log("需要输入密码", parseFloat(this.userInfo.moneyWithoutCode) < realPay);
              this.$refs.pro.showOrHide();
            }
          }
          this.storeOrderNo = req.data.data[0].storeOrderNo;
        }
        if(req.data.returnCode === 0){
          // this.stopIntervalAjax();
          // Toast({
          //   message: req.data.msg || "查询待支付订单异常！",
          //   type: 'success',
          //   duration: api.alertTime_2
          // })
        }
        if(req.data.returnCode === 2){
          // Toast({
          //   message: req.data.msg || "没有可支付订单！",
          //   type: 'success',
          //   duration: api.alertTime_2
          // })
          // this.stopIntervalAjax();
        }
      },
      // 开启轮询获取支付动作
      startIntervalAjax() {
        this.timer = setInterval(() => {
          this.getOrderResult()
        }, this.intervalTiming);
      },
      //结束轮询
      stopIntervalAjax() {
        clearInterval(this.timer);
        this.timer = null;
      },
      //处理密码输入相关的方法
      handle(data) {
        console.log("密码输入完毕，这里在调用", data);
        let val = '';
        if(data.result) {
          //check password success;
          // Toast({
          //   message: data.msg,
          //   type: 'success',
          //   duration: api.alertTime_2
          // })
          val = 1;
          this.sendStatus(val);
          // return
        }else if(!data.response){
          //input password timeout;
          Toast({
            message: data.msg,
            type: 'fail',
            duration: api.alertTime_2
          })
          val = 4;
          // return
        } else {
          Toast({
            message: data.msg,
            type: 'fail',
            duration: api.alertTime_2
          })
          val = 4;
          // return
        }

        // this.sendStatus(val);
      },
      //取消输入密码
      cancelPassword() {
        window.history.go(-1);
        this.cancelOrderFn();
      },
      //取消订单
      cancelOrderFn() {
        let val = 4;
        this.sendStatus(val);
      },
      async sendStatus(state){
        let param = {
          "payStatus":state,
          "storeOrderNo":this.storeOrderNo
        }
        let req = await walletPayOffLineOrder(param);
        //支付成功
        if(req.data.returnCode === 1){
          Toast({
            message: req.data.msg || "支付成功！",
            type: 'success',
            duration: api.alertTime_2
          })
          // 将this.needCancelOrder置为false
          this.needCancelOrder = false;
        }
        //支付失败或者取消支付，需要继续开启轮询
        if(req.data.returnCode === 0){
          Toast({
            message: req.data.msg || "支付失败，稍后再试！",
            type: 'fail',
            duration: api.alertTime_2
          })
          //开启轮询
          this.startIntervalAjax();
        }
        if (req.data.returnCode === 2) {
          // 将this.needCancelOrder置为false
          this.needCancelOrder = false;
          Toast({
            message: "支付已取消",
            type: 'warn',
            duration: api.alertTime_2
          })
          //开启轮询
          // this.startIntervalAjax();
        }
      },
      //提示的方法
      mToast(message, type = "success", duration = "1500") {
        Toast({
          message,
          type,
          duration
        });
      }
    }
  }
</script>

<style scoped>
.customHeaderStyle{
		position: relative;
		background: #fff;
		min-height: 3rem;
		border-bottom: 1px solid #eaeaea;
		color: #444;
		font-weight: 700;
		left: 0;
		top: 0;
		line-height: 2.25rem;
		/* z-index: 2; */
		width: 100%;
		font-size: .9rem;
		text-align: center;
		margin: 0;
		padding: 0;
	}
	.headerCustomTitle{
		overflow: hidden;
		right: 6rem;
		font-weight: 500;
		min-height: 2.25rem;
		position: absolute;
		margin: 0;
		text-align: left;
		white-space: nowrap;
		left: 3rem;
		width: auto;
		text-overflow: ellipsis;
		z-index: 2;
		font-size: 1.1rem;
		margin-top: .35rem;
		top: 1px;
	}
  #app {
    background: #fff;
  }

  .container {
    height: 100%;
    background: rgba(41, 154, 40, 1);
  }

  .wrapper {
    position: relative;
    width: 100%;
    /* height: 100%; */
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    /* top: 10%; */
    height: 90%;
  }

  .inner {
    background: #fff;
    width: 90%;
    /*margin: auto;*/
    /*margin-top: 2rem;*/
    position: relative;
    /*top: 10%;*/
    /*transform: translateY(-80%);*/
  }

  #qr {
    width: 100%;
    height: 100%;
    margin: auto;
    padding-top: 2rem;
    display: flex;
    justify-content: space-around;
  }

  #qr img {
    height: 50%;
    width: 60%;
  }

  #ean {
    margin-top: 2rem;
  }

  .pay_method {
    height: 2.5rem;
    margin-top: 1rem;
    font-size: 0.8rem;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .tip_2 {
    /*margin-top: 9rem;*/
    color: #fff;
  }

  .njfont {
    margin-right: 0.3rem;
    font-size: 1.2rem;
    color: #f4b419;
  }
</style>
